package com.itgacl.minio;

import com.itgacl.minio.config.MinioConfig;
import com.itgacl.minio.policy.BucketPolicyFactory;
import io.minio.*;
import io.minio.errors.*;
import io.minio.messages.Item;
import lombok.extern.slf4j.Slf4j;

import javax.activation.MimetypesFileTypeMap;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

@Slf4j
public class MinioService {

    private final MinioConfig minioConfig;

    private MinioClient minioClient;


    /**
     * bucket权限-读写
     */
    public MinioService(MinioConfig minioConfig){
        this.minioConfig = minioConfig;
        try {
            //构建MinioClient
            minioClient = MinioClient.builder()
                    .endpoint(minioConfig.getEndpoint())
                    .credentials(minioConfig.getAccessKey(), minioConfig.getSecretKey())
                    .build();
            createBucket(minioConfig.getBucketName());
        } catch (Exception e) {
            log.error("创建minio桶出错："+e.getMessage(),e);
        }
    }

    /**
     * 判断桶是否存在
     * @param bucketName
     * @return
     */
    public boolean isExists(String bucketName){
        try {
            return minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
        return false;
    }

    /**
     * 创建bucket
     * @param bucketName 桶名
     * @throws Exception
     */
    public void createBucket(String bucketName) throws Exception {
        if (!isExists(bucketName)) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            //设置访问策略
            boolean retResult = BucketPolicyFactory.getBucketPolicy(minioConfig.getBucketPolicy()).createBucketPolicy(minioClient, bucketName);
            log.debug("创建minio桶:{}，设置访问策略结果：{}",bucketName,retResult);
        }
    }


    /**
     * 列出存储桶中的所有对象
     * @param bucketName
     * @return
     */
    public Iterable<Result<Item>> listObjects(String bucketName) {
        boolean flag = isExists(bucketName);
        if (flag) {
            return minioClient.listObjects(ListObjectsArgs.builder().bucket(bucketName).build());
        }
        return null;
    }

    /**
     * 删除桶
     * @param bucketName
     * @return
     * @throws Exception
     */
    public boolean removeBucket(String bucketName) throws Exception {
        boolean flag = isExists(bucketName);
        if (flag) {
            Iterable<Result<Item>> myObjects = listObjects(bucketName);
            for (Result<Item> result : myObjects) {
                Item item = result.get();
                // 有对象文件，则删除失败
                if (item.size() > 0) {
                    return false;
                }
            }
            // 删除存储桶，注意，只有存储桶为空时才能删除成功。
            minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());
            flag = isExists(bucketName);
            return !flag;
        }
        return false;
    }


    /**
     * 上传文件
     * @param filePath
     * @param bucketName
     * @throws Exception
     */
    public String uploadFile(String filePath, String bucketName, String fileName,String contentType) throws Exception {
        ObjectWriteResponse uploadObject = minioClient.uploadObject(
                UploadObjectArgs.builder()
                        .bucket(bucketName)
                        .object(fileName)
                        .filename(filePath)
                        .contentType(contentType)
                        .build());
        log.debug("uploadObject:{}",uploadObject);
        String httpAccessUrl = minioConfig.getEndpoint()+"/"+bucketName+"/"+fileName;
        return httpAccessUrl;
    }

    /**
     * 上传文件
     * @param inputStream
     * @param bucketName
     * @throws Exception
     */
    public String uploadFile(InputStream inputStream, String bucketName, String fileName,String contentType) throws Exception {
        minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(bucketName)
                        .object(fileName)
                        .stream(inputStream,inputStream.available(),-1)
                        .contentType(contentType)
                        .build()
        );
        String httpAccessUrl = minioConfig.getEndpoint()+"/"+bucketName+"/"+fileName;
        return httpAccessUrl;
    }

    /**
     * 上传文件
     * @param bucketName
     * @throws Exception
     */
    public String uploadFile(byte[] fileBytes, String bucketName, String fileName,String contentType) throws Exception {
        InputStream inputStream = new ByteArrayInputStream(fileBytes);
        return uploadFile(inputStream,bucketName,fileName,contentType);
    }

    /**
     * 上传文件
     * @param fileBytes
     * @param fileName
     * @throws Exception
     */
    public String uploadFile(byte[] fileBytes, String fileName,String contentType) throws Exception {
       return uploadFile(fileBytes,minioConfig.getBucketName(),fileName,contentType);
    }

    /**
     * 上传文件
     * @param inputStream
     * @throws Exception
     */
    public String uploadFile(InputStream inputStream, String fileName,String contentType) throws Exception {
       return uploadFile(inputStream,minioConfig.getBucketName(),fileName,contentType);
    }

    /**
     * 上传文件
     * @param filePath
     * @throws Exception
     */
    public String uploadFile(String filePath, String fileName,String contentType) throws Exception {
       return uploadFile(filePath,minioConfig.getBucketName(),fileName,contentType);
    }

    /**
     * 上传文件
     * @param filePath
     * @throws Exception
     */
    public String uploadFile(String filePath) throws Exception {
        File oldFile = new File(filePath);
        //文件名
        String originalFilename = oldFile.getName();
        //新的文件名 = 存储桶文件名_时间戳_UUID.后缀名
        String newFileName = minioConfig.getBucketName() + "_" +
                System.currentTimeMillis() +
                originalFilename.substring(originalFilename.lastIndexOf("."));
        String contentType = new MimetypesFileTypeMap().getContentType(oldFile);
        return uploadFile(filePath,newFileName,contentType);
    }

    /**
     * 删除文件
     * @param fileName 文件名
     * @param bucket 桶名
     * @return
     */
    public boolean removeFile(String fileName, String bucket) {
        try {
            minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucket).object(fileName).build());
            return true;
        } catch (InvalidKeyException | ErrorResponseException | InsufficientDataException | InternalException
                | InvalidResponseException | NoSuchAlgorithmException | ServerException | XmlParserException
                | IllegalArgumentException | IOException e) {
            e.printStackTrace();
            log.error("error: {}", e.getMessage(), e);
        }
        return false;
    }

    /**
     * 删除文件
     * @param fileName 文件名
     * @return
     */
    public boolean removeFile(String fileName) {
        return removeFile(fileName,minioConfig.getBucketName());
    }

    /**
     * 下载文件
     * @param fileName 文件名
     * @param bucket 桶名
     * @return 返回文件流
     */
    public InputStream downloadFile(String fileName, String bucket) {
        try {
            // 返回文件流
            return minioClient.getObject(GetObjectArgs.builder().bucket(bucket).object(fileName).build());
        } catch (InvalidKeyException | ErrorResponseException | InsufficientDataException | InternalException
                | InvalidResponseException | NoSuchAlgorithmException | ServerException | XmlParserException
                | IllegalArgumentException | IOException e) {
            log.error("error: {}", e.getMessage(), e);
        }
        return null;
    }

    /**
     * 下载文件
     * @param fileName 文件名
     * @return 返回文件流
     */
    public InputStream downloadFile(String fileName) {
        return downloadFile(fileName,minioConfig.getBucketName());
    }
}
